import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button, InputNumber } from 'antd';
import styles from './Users.css';
import moment from 'moment';
import Factory from '../factory';
import * as datetime from '../../utils/datetime'
import dataEditCreate from '../addons/DataEdit'
import dataTableCreate from '../addons/DataTable'
import dataImportCreate from '../addons/DataImport'
import * as menuService from '../../services/menus';
import * as common from '../../utils/common';
import * as setMnlrYc from '../../services/other';
const daoName = "LRYC";
const ButtonGroup = Button.Group;
const columns = [
  { title: '经营单位', width: 120, sorter: true, key: 'UTNM', dataIndex: 'UTNM', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '1月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR1', dataIndex: 'MNLR1', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '2月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR2', dataIndex: 'MNLR2', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '3月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR3', dataIndex: 'MNLR3', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '4月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR4', dataIndex: 'MNLR4', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '5月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR5', dataIndex: 'MNLR5', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '6月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR6', dataIndex: 'MNLR6', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '7月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR7', dataIndex: 'MNLR7', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '8月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR8', dataIndex: 'MNLR8', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '9月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR9', dataIndex: 'MNLR9', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '10月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR10', dataIndex: 'MNLR10', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '11月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR11', dataIndex: 'MNLR11', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '12月考核利润', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLR12', dataIndex: 'MNLR12', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '考核利润合计', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLRHJ', dataIndex: 'MNLRHJ', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '利润指标', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLRZB', dataIndex: 'MNLRZB', dispaly: true, canEdit: true, filter: true, export: true },
  { title: '较指标缺口', width: 180, sorter: true, className: 'column-money', render: data => common.formatNumber2(data), key: 'MNLRCE', dataIndex: 'MNLRCE', dispaly: true, canEdit: true, filter: true, export: true },
];
let controls = [
  { name: 'UTNM', required: true, type: 'text', label: '经营单位', min: 1, max: 50, grid: 12 / 24 },
  { name: 'MNLR1', required: true, type: 'number', label: '1月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR2', required: true, type: 'number', label: '2月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR3', required: true, type: 'number', label: '3月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR4', required: true, type: 'number', label: '4月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR5', required: true, type: 'number', label: '5月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR6', required: true, type: 'number', label: '6月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR7', required: true, type: 'number', label: '7月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR8', required: true, type: 'number', label: '8月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR9', required: true, type: 'number', label: '9月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR10', required: true, type: 'number', label: '10月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR11', required: true, type: 'number', label: '11月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLR12', required: true, type: 'number', label: '12月考核利润', grid: 12 / 24, dataType: "number" },
  { name: 'MNLRHJ', required: true, type: 'number', label: '考核利润合计', grid: 12 / 24, dataType: "number" },
  { name: 'MNLRZB', required: true, type: 'number', label: '利润指标', grid: 12 / 24, dataType: "number" },
  { name: 'MNLRCE', required: true, type: 'number', label: '较指标缺口', grid: 12 / 24, dataType: "number" },
];

const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class LRYCForecastForm extends Component {
  constructor(props) {
    super(props);
    const myDate = new Date();
    const nf = myDate.getFullYear();
    this.state = {
      dataChange: false,
      nf,
      ycyf: 12
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "UTID", permID: this.props.permID }
    });
    this.loadData();
    this.loadOptionData();
  }
  onNfChange(value) {
    this.state.nf = Number(value)
  }
  onYcyfChange(value) {
    this.state.ycyf = Number(value)
  }
  loadData() {
    this.props.dispatch({
      type: `${daoName}/fetchMaxdryf`,
      payload: { nf: this.state.nf }
    });
    let seeks = [{
      WhereItems: [{
        FieldName: "NF",
        Operator: "=",
        FieldValues: '' + this.state.nf
      }],
      RelationSign: "AND"
    }]
    let { permID, pOrgID, popedomTypes } = this.props
    const pTypes = popedomTypes[permID]
    if (pTypes.indexOf("4") == -1) {
      let orgID = "0"
      if (pTypes.indexOf("L") == -1) {
        orgID = "" + pOrgID
      }
      seeks[0].WhereItems.push({
        FieldName: "UTID",
        Operator: "=",
        FieldValues: orgID
      })
    }
    let sort = {
      field: 'OrderKey'
    }
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 30, seeks, ycyf: this.state.ycyf, sorter: sort }
    });
    setMnlrYc.setMnlrYc({ yf: this.state.ycyf });
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  showModelHandler(isAdd) {
    let key = null
    if (!isAdd) {
      const len = this.props.selectedRowKeys.length;
      if (len === 0) {
        message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
        return;
      }
      key = this.props.selectedRowKeys[len - 1]
    }
    this.props.dispatch({
      type: `${daoName}/openEdit`,
      payload: { key }
    });
  }
  deleteHandler() {
    const keys = this.props.selectedRowKeys;
    const len = keys.length;
    if (len === 0) {
      message.info('请选择要删除的行！');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: `你确认要删除选中的${len}行数据吗？`,
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: `${daoName}/remove`,
          payload: { daoName, keys },
        });
      }
    });
  }
  edidOkHandler() {
    const form = this.refs.OrganForm.getForm()
    form.validateFields((err, values) => {
      if (!err) {
        let t = `${daoName}/create`
        const { keyName, record } = this.props;
        let msg = "数据添加成功！"
        if (record[keyName]) {
          values[keyName] = record[keyName];
          t = `${daoName}/patch`
          msg = "数据修改成功！"
        }
        controls.map((c, i) => {
          if (c.type === 'cascader-select') {
            let vs = values[c.name];
            if (vs.length > 0) {
              values[c.name] = vs[vs.length - 1];
            } else {
              values[c.name] = null;
            }
          }
          if (c.dataType === "number") {
            values[c.name] = Number(values[c.name])
          } else if (c.dataType === "date" || c.dataType === "datetime") {
            values[c.name] = !values[c.name] ? null : new Date(values[c.name])
          } else {
            values[c.name] = values[c.name] === undefined ? null : values[c.name]
          }
          if (c.multiple || c.type === 'checkbox-group') {
            values[c.name] = values[c.name].join(',');
          }
        })
        this.state.dataChange = true;
        this.props.dispatch({
          type: t,
          payload: { daoName, values },
        })
      }
    });
  };
  hideEditHandler() {
    const form = this.refs.OrganForm.getForm();
    form.resetFields();
    if (this.state.dataChange) {
      this.props.dispatch({
        type: `${daoName}/reload`,
        payload: { daoName },
      });
      this.state.dataChange = false;
    }
    this.props.dispatch({
      type: `${daoName}/hideEdit`
    });
  };
  render() {
    let { showEdit, record, permID, popedomTypes, maxdryf } = this.props
    const pTypes = popedomTypes[permID]
    let cols = []
    cols.push(columns[0])
    if (maxdryf) {
      for (let i = 1; i <= 12; i++) {
        let title = `${i}月考核利润`
        if (i > maxdryf) {
          columns[i].title = title + "预测"
        } else {
          columns[i].title = title
        }
        const ycyf = this.state.ycyf
        if (i <= ycyf) {
          cols.push(columns[i])
        }
      }
    }
    cols.push(columns[13])
    cols.push(columns[14])
    cols.push(columns[15])
    let data = null
    data = <ButtonGroup style={{ zIndex: 0 }}>
      <span>年份:</span>
      <InputNumber defaultValue={this.state.nf} style={{ marginLeft: 10, marginRight: 10, width: 80 }} onChange={this.onNfChange.bind(this)} />
      <span>预测月份:</span>
      <InputNumber min={2} max={12} defaultValue={this.state.ycyf} style={{ marginLeft: 10, marginRight: 10, width: 50 }} onChange={this.onYcyfChange.bind(this)} />
      <Button onClick={this.loadData.bind(this)}>查询</Button>
    </ButtonGroup>
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}>
            {data}
            <div style={{ float: "right" }}><span>单位：万元</span><span style={{ marginLeft: 40 }}>说明：预测月份利润按照月人民币公司存贷款+月本外币储蓄+月个贷利润的平均值预测</span></div>
          </div>
          <Modal title="机构编辑" width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)}
            footer={[
              <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
              <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
            ]}
          >
            <EditFrom ref="OrganForm" daoName={daoName} controls={controls} record={record} />
          </Modal>
          <DataTable ref="OrganTable" daoName={daoName} columns={cols} controls={controls} permID={permID} />
        </div>
      </div>
    )
  }
}
function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName, maxdryf } = state[daoName];
  const { userID, orgID, pOrgID, popedomTypes } = state.menus;
  return {
    userID,
    orgID,
    pOrgID,
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record,
    maxdryf
  }
}
LRYCForecastForm = connect(mapStateToProps)(LRYCForecastForm)
export default LRYCForecastForm;

let render = (props) => React.createElement(LRYCForecastForm, props);
let f = new Factory()
f.set("LRYCForecastForm", render)
